package algorithms;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class Zip implements LosslessCompressionAlgorithm
{
	java.lang.String _extension = "zip";

	@Override
	public void encode(File filenameIn, File filenameOut) throws java.io.IOException {
		
		ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(filenameOut));
		FileInputStream fileIn = new FileInputStream(filenameIn);
		zipFile.setMethod(ZipOutputStream.DEFLATED);
		zipFile.setLevel(9);
		byte[] buffer = new byte[1024];
		int byteRead;
		zipFile.putNextEntry(new ZipEntry(filenameIn.getName()));
		while ((byteRead = fileIn.read(buffer)) != -1 )
		{
			zipFile.write(buffer, 0, byteRead);
		}
		fileIn.close();		
		zipFile.close();
	}

	@Override
	public void decode(File fileIn, File fileOut) throws java.io.IOException {

		ZipInputStream zipFile = new ZipInputStream(new FileInputStream(fileIn));
		FileOutputStream unzipFile = null;
		
		int nrBytesRead;
		byte[] buffer = new byte[4096];
		
		ZipEntry entry;
		while ((entry = zipFile.getNextEntry()) != null)
		{
			unzipFile = new FileOutputStream(entry.getName());
			while((nrBytesRead = zipFile.read(buffer)) != -1)
			{
				unzipFile.write(buffer, 0, nrBytesRead);
			}
		}
		zipFile.closeEntry();
		zipFile.close();
	}

	@Override
	public String getFileExtension() {
		return _extension;
	}

	@Override
	public void setFileExtension(java.lang.String name) {
		_extension = name;
	}

}
